var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var path = require('path');

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); // 在parse传入参数的同时去不限定最大长度，使之能够上传base64的图片，超过110k

var emptyDir = function (fileUrl) {
  var files = fs.readdirSync(fileUrl);//读取该文件夹
  files.forEach(function (file) {
    var stats = fs.statSync(fileUrl + '/' + file);
    if (stats.isDirectory()) {
      emptyDir(fileUrl + '/' + file);
    } else {
      fs.unlinkSync(fileUrl + '/' + file);
      console.log("删除文件" + fileUrl + '/' + file + "成功");
    }
  });
}

// 读取评论
app.get('/api/getComment', function (req, res) {
  console.log('请求进来了')
  const query = req.query || {}
  const fileName = __dirname + '/json/' + 'comment.json'
  fs.readFile(fileName, 'utf8', function (err, data) {
    res.end(data)
  })
})

app.post('/api/addComment', function (req, res) {
  const fileName = __dirname + '/json/' + 'comment.json'
  fs.readFile(fileName, 'utf8', function (err, data) {
    data = JSON.parse(data)
    var newData = req.body.comment
    data.comment.push({
      value: newData
    })
    fs.writeFile(fileName, JSON.stringify(data), function (err) {
      if (err) {
        console.log(err)
      } else {
        console.log('文件修改成功')
        res.end(JSON.stringify(data))
      }
    })
  })
})

// 首页的标题和图片
app.get('/api/listUsers', function (req, res) {
  res.send('hahah');
})

app.post('/api/listUsers2', function (req, res) {
  var imgData = req.body.a
  var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
  var dataBuffer = new Buffer(base64Data, 'base64');
  fs.writeFile("img/out.png", dataBuffer, function (err) { // 读入文件夹
    if (err) {
      res.send(err);
    } else {
      res.send(req.body)
    }
  });
})

// phantomjs 截图
app.get('/api/getImg', function (req, res) {

  const phantom = require('./../node_modules/phantom');

  (async function () {
    var reqData = [ // 传过来的数据
      {
        name: 'pie-charts111',
        sample: 46,
        Employer: 90,
        id: 1 // 图片id
      },
      {
        name: 'blue-pic333',
        canvas2Data: '呵呵哈巴狗',
        id: 2
      },
      {
        name: 'red-pic222',
        canvas3Data: 3434,
        id: 3
      },
      {
        name: 'green-pic33344',
        canvas4Data: '爱上答案打撒阿斯达',
        id: 4
      }
    ]
    var url = 'http://localhost:8080/#/echarts/dedicate?'
    for (var i = 0; i < reqData.length; i++) {
      const a = reqData[i]
      for (var j in a) {
        if (j === 'id') {
        } else if (j !== 'name') {
          url += j + '=' + encodeURIComponent(a[j]) + '&'
        } else {
          url += 'name-' + a['id'] + '=' + encodeURIComponent(a[j]) + '&'
        }
      }
    }
    console.log(11, url)
    const instance = await phantom.create();
    const page = await instance.createPage();
    page.property('viewportSize', { width: 1280, height: 8000 })
    const status = await page.open(url);
    if (status === 'success') {
      console.log('网页打开')
      setTimeout(function () {
        page.evaluate(function () { // 这里读不到外面的变量
          var reqList = document.querySelectorAll('.block')
          var arr = []
          for (var i = 0; i < reqList.length; i++) {
            var div = reqList[i].querySelector('.container')
            var bc = div.getBoundingClientRect();
            var top = bc.top;
            var left = bc.left;
            var width = bc.width;
            var height = bc.height;
            arr.push({
              name: reqList[i].querySelector('.imgName').innerText,
              top: top,
              left: left,
              width: width,
              height: height
            })
          }
          return arr
        }).then(function (arr) {
          emptyDir('./img')
          console.log('大小参数', arr)
          for (var i = 0; i < arr.length; i++) {
            var a = arr[i]
            page.property('clipRect', { //截图的偏移和宽高  
              top: a.top,
              left: a.left,
              width: a.width,
              height: a.height
            })
            const urlPath = './img/' + a.name + '.png'
            page.render(urlPath)
          }
          // page.renderBase64('PNG').then(function (aaaa) {
          //   res.send(aaaa)
          // })
          res.send('图片生成成功')
          console.log('截图完成')
          instance.exit();
        })
      }, 2000)
    }
  })();
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("应用实例，访问地址为 http://%s:%s", host, port)

})